package xmlsync2;

import java.io.UnsupportedEncodingException;
import java.sql.DatabaseMetaData;
import java.sql.Date;
import java.sql.Time;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.MessageFormat;
import java.util.Calendar;
import java.util.LinkedList;
import org.apache.log4j.Logger;
import datawave.util.LoggerCache;

public class Str
{
	static private char[] SPECIALCHAR = {'!','@','#','$','%','^','&','*','(',')'};
	static private char[] NUMBERCHAR = {'0','1','2','3','4','5','6','7','8','9'};
	static private char[] ALPHABETCHAR = {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'};
	static private boolean ISO8859 = true;													 
	static private Logger log = LoggerCache.get(Session.class.getName());

	static public String trimleft(final String source, final char target)
	{
		int i=0;
		while (i < source.length() && source.charAt(i)==target) i++;
		return source.substring(i);
	}
	
	public static String extract(final String key, final String dsn)
	{
		String lowercase = dsn.toLowerCase();
		int pos = lowercase.indexOf(key+"=");
		if (pos < 0) return null;
		int end = dsn.indexOf(";", pos);
		if (end < 0) return dsn.substring(pos+key.length()+1);
		else return dsn.substring(pos+key.length()+1, end);
	}

	public static String getcurrenttime()
	{
		return DateFormat.getDateTimeInstance().format(Calendar.getInstance().getTime());
	}
	
	public static String dateformat(final Date date)
	{// 2002-07-20T20:12.32
		if (date == null) return null;
		else return date.toString().replace(' ', 'T').replace('/', '-');
	}

	static public String trimright(final String source, final char target)
	{
		int i = source.length() - 1;
		while (i>=0 && source.charAt(i)==target) i--;
		return source.substring(0, i+1);	
	}

	static public String trim(final String source, final char target)
	{
		return trimright(trimleft(source, target), target);
	}
	
	static public boolean isquoted(final String source)
	{
		return source.startsWith("'") && source.endsWith("'");
	}
	
	static String catalogof(final String str)
	{
		int pos = str.indexOf('.');
		if (pos < 0) return null;
		else return str.substring(0, pos);		
	}

	static String replace(final String source, final String name, final String value)
	{
		int pos = source.indexOf(name);
		if (pos < 0) return source;
		else return source.substring(0, pos) + value + replace(source.substring(pos+name.length()), name, value);
	}
	
	static String procedurenameof(final String str)
	{
		int pos = str.indexOf('.');
		if (pos < 0) return str;
		else return str.substring(pos+1);
	}

	static String headof(final String str, final char delimeter)
	{
		int pos = str.indexOf(delimeter);
		if (pos < 0) return str;
		else return str.substring(0, pos);
	}
	
	static String tailof(final String str, final char delimeter)
	{
		int pos = str.indexOf(delimeter);
		if (pos < 0) return "";
		else return str.substring(pos+1);
	}
	
	static String nameof(final String xpath)
	{
		int pos = xpath.indexOf("[");
		if (pos < 0) return xpath;
		else return xpath.substring(0, pos);
	}
	
	static String predicateof(final String xpath)
	{
		int pos = xpath.indexOf("[");
		if (pos < 0) return "";
		else return xpath.substring(pos+1, xpath.length()-1);
	}
	
	static public boolean isnumber(final String source)
	{
		try
		{
			Integer.parseInt(source);
		}
		catch (Exception e)
		{
			return false;
		}
		return true;
	}
	
	static public LinkedList buildlist(final String script, final String delimeter)
	{
		LinkedList list = new LinkedList();
		String str = script.trim();
		if (str.length()>0)
		{
			int pos = str.indexOf(delimeter);
			if (pos < 0)
				list.addLast(str);
			else 
			{
				list.addLast(str.substring(0, pos));
				list.addAll(buildlist(str.substring(pos+1), delimeter));
			}
		}
		return list;
	}
	/**
	 * Method sql.
	 * @param string
	 * @param type
	 * @param paramcount
	 * @return String
	 */
	public static String sql(final String name, final short type, final int paramcount)
	{
		switch (type)
		{
			case DatabaseMetaData.procedureNoResult :
				return "{call "+procedure(name, paramcount)+"}";
			default :
				return "{? = call "+ procedure(name, paramcount)+"}";
		}
	}

	private static String procedure(final String name, final int paramcount)
	{
		return name + " ("+questionmark(paramcount)+")";
	}

	/**
	 * Method questionmark.
	 * @param paramcount
	 * @return String
	 */
	private static String questionmark(int paramcount)
	{
		if (paramcount == 0) return "";
		String str = "?";
		for(int i=1; i<paramcount; i++)
			str += ", ?";
		return str;	
	}

	/**
	 * Method getdate.
	 * @param value
	 * @return Date
	 */
	public static Date getdate(final String value)
	{
		if (value.indexOf('T')<0)
			return Date.valueOf(value.replace('/','-'));
		else return Date.valueOf(value.substring(0, value.indexOf('T')).replace('/','-'));
	}
	/**
	 * Method gettime.
	 * @param value
	 * @return Time
	 */
	public static Time gettime(final String value)
	{
		if (value.indexOf('T')<0)
			return Time.valueOf(value.replace('.',':'));
		else return Time.valueOf(value.substring(value.indexOf('T')+1).replace('.',':'));
	}

	/**
	 * Method gettimestamp.
	 * @param value
	 * @return Timestamp
	 */
	public static Timestamp gettimestamp(final String value)
	{
		return Timestamp.valueOf(value.replace('/','-').replace('.',':').replace('T',' '));
	}

	public static char randomchoose(final char[] domain)
	{
		return domain[(int)(Math.random()*domain.length)];
	}
	public static String random()
	{
		String random = "";
		for (int i=0; i<5; i++)
			random += randomchoose(ALPHABETCHAR);
		for (int i=0; i<1; i++)
			random += randomchoose(SPECIALCHAR);
		for (int i=0; i<2; i++)
			random += randomchoose(NUMBERCHAR);
		return shuffle(shuffle(shuffle(random)));
	}

	/**
	 * Method shuffle.
	 * @param random
	 */
	private static String shuffle(final String random)
	{
		int pos = (int)(Math.random()*random.length());
		return random.substring(pos) + random.substring(0, pos);
	}

	/**
	 * Method systemencode.
	 * @param string
	 * @return String
	 */
	public static String systemencode(final String str)
	{
		if (ISO8859)
			try
			{
				return new String(str.getBytes("EUC-KR"), "ISO8859_1");
			}
			catch (UnsupportedEncodingException e)
			{
				return str;
			}
		else return str;
	}

	/**
	 * Method decode.
	 * @param string
	 * @param encoding
	 * @return String
	 */
	public static String decode(String string, String encoding)
	{
		try
		{
			return new String(string.getBytes(encoding), "euc-kr");
		}
		catch (UnsupportedEncodingException e)
		{
			Object[] args = {e.getMessage()};
			String msg = MessageFormat.format(Messages.getString("XMLSYNC0007"), args);
			log.error(msg);
			return string;
		}
	}

}